# coding:utf-8

"""
image_util
Created on 2016/12/7 16:45
@author: GuoYufu
@group : OceanHorn
@contact: OceanHorn@163.com
"""

import numpy as np
import matplotlib.pyplot as plt

class Image_util:

    @classmethod
    def reform(cls, samples, labels):
        samples = Image_util.__transform(samples)
        labels = Image_util.__reform_labels(labels)
        return  samples, labels

    @classmethod
    def __transform(cls, samples):
        samples = np.transpose(samples, (3, 0, 1, 2))
        return  samples

    @classmethod
    def __reform_labels(cls, labels):
        labels = np.array([x[0] for x in labels])

        one_hot_labels = []
        for num in labels:
            one_hot = [0.0] * 10
            if num == 10:
                one_hot[0] = 1.0
            else:
                one_hot[num] = 1.0
            one_hot_labels.append(one_hot)

        labels = np.array(one_hot_labels).astype(np.float32)
        return labels

    @classmethod
    def normalize(cls, samples):
        reduce_result = np.add.reduce(samples, keepdims=True, axis=3)  # shape (图片数，图片高，图片宽，通道数)
        reduce_result = reduce_result / 3.0
        return reduce_result / 128.0 - 1.0

    @classmethod
    def distribution_reformed(cls, labels, name):
        count = {}
        for label in labels:
            index = 0
            for tag in label:
                if tag == 1.0:
                    if index in count:
                        count[index] += 1
                    else:
                        count[index] = 1
                index += 1
        x = []
        y = []
        for k, v in count.items():
            # print(k, v)
            x.append(k)
            y.append(v)

        Image_util.__show_plot(x, y, name)

    @classmethod
    def distribution(cls, labels, name):
        # 查看一下每个label的分布，再画个统计图
        # keys:
        # 0
        # 1
        # 2
        # ...
        # 9
        count = {}
        for label in labels:
            key = 0 if label[0] == 10 else label[0]
            if key in count:
                count[key] += 1
            else:
                count[key] = 1
        x = []
        y = []
        for k, v in count.items():
            # print(k, v)
            x.append(k)
            y.append(v)

        Image_util.__show_plot(x, y, name)

    @classmethod
    def __show_plot(cls, x, y, name):
        y_pos = np.arange(len(x))
        plt.bar(y_pos, y, align='center', alpha=0.5)
        plt.xticks(y_pos, x)
        plt.ylabel('Count')
        plt.title(name + ' Label Distribution')
        plt.show()


    @classmethod
    def inspect(cls, samples, labels, i):
        # 显示图片看看
        if samples.shape[3] == 1:
            shape = samples.shape
            samples = samples.reshape(shape[0], shape[1], shape[2])
        print(labels[i])
        plt.imshow(samples[i])
        plt.show()